package com.whiteblue.controller;

import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.whiteblue.interceptor.AdminInterceptor;
import com.whiteblue.interceptor.LoginInterceptor;
import com.whiteblue.model.Module;
import com.whiteblue.model.Post;
import com.whiteblue.model.Topic;
import com.whiteblue.validator.PostValidator;
import com.whiteblue.validator.TopicValidator;

/**
 * Created with IntelliJ IDEA.
 */
public class TopicController extends Controller {
	public void index() {
		forwardAction("/post/" + getParaToInt(0));
	}

	public void list() {
		setAttr("actionUrl", "/topic/list");
		render("/module_list.html");
	}

	// 得到module分组中的所有topic
	public void module() {
		setAttr("topicPage",
				Topic.dao.getPageForModule(getParaToInt(0), getParaToInt(1, 1)));
		setAttr("actionUrl", "/topic/module/" + getParaToInt(0) + "-");
		setAttr("module_name", Module.dao.getName(getParaToInt(0)));
		render("/topic.html");
	}

	public void hot() {
		setAttr("topicPage", Topic.dao.getHotPage(getParaToInt(0, 1)));
		setAttr("actionUrl", "/topic/hot/");
		setAttr("module_name", "Hot");
		render("/topic.html");
	}

	public void nice() {
		setAttr("topicPage", Topic.dao.getNicePage(getParaToInt(0, 1)));
		setAttr("actionUrl", "/topic/nice/");
		setAttr("module_name", "Jing Pin");
		render("/topic.html");
	}

	@Before(LoginInterceptor.class)
	public void add() {
		render("/addTopic.html");
	}

	@Before({ LoginInterceptor.class, TopicValidator.class, PostValidator.class })
	public void save() {
		Topic topic = getModel(Topic.class);
		topic.set("userID", getSessionAttr("userID")).set("id", null);
		Post post = getModel(Post.class);
		post.set("userID", getSessionAttr("userID"));
		topic.save(post);
		redirect("/post/" + topic.getInt("id"));
	}

	@Before(AdminInterceptor.class)
	public void edit() {
		Topic topic = Topic.dao.get(getParaToInt(0));
		setAttr("topic", topic);
		render("/topic/edit.html");
	}

	@Before({ AdminInterceptor.class, TopicValidator.class })
	public void update() {
		getModel(Topic.class).myUpdate();
		redirect("/post/" + getParaToInt("topic.id"));
	}

	@Before(AdminInterceptor.class)
	public void delete() {
		Topic.dao.deleteByID(getParaToInt(0));
		forwardAction("/admin/topicList/" + getParaToInt(1));
	}
}
